<template>
	<view class="container">
		<!-- 总览卡片 -->
		<view class="overview-section">
			<view class="stats-card">
				<view class="stats-grid">
					<view class="stat-item">
						<text class="stat-number">{{ statistics.total }}</text>
						<text class="stat-label">总日程</text>
					</view>
					<view class="stat-item">
						<text class="stat-number completed">{{ statistics.completed }}</text>
						<text class="stat-label">已完成</text>
					</view>
					<view class="stat-item">
						<text class="stat-number urgent">{{ statistics.urgent }}</text>
						<text class="stat-label">紧急待办</text>
					</view>
					<view class="stat-item">
						<text class="stat-number overdue">{{ statistics.overdue }}</text>
						<text class="stat-label">已过期</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 完成率 -->
		<view class="completion-section">
			<view class="section-header">
				<text class="section-title">完成率</text>
			</view>
			<view class="completion-card">
				<view class="progress-circle">
					<view class="circle-bg">
						<view 
							class="circle-fill" 
							:style="{ 
								transform: `rotate(${completionDegree}deg)` 
							}"
						></view>
					</view>
					<view class="circle-content">
						<text class="percentage">{{ statistics.completionRate }}%</text>
						<text class="percentage-label">完成率</text>
					</view>
				</view>
				<view class="completion-details">
					<view class="detail-item">
						<view class="detail-dot completed"></view>
						<text class="detail-text">已完成 {{ statistics.completed }}</text>
					</view>
					<view class="detail-item">
						<view class="detail-dot pending"></view>
						<text class="detail-text">待完成 {{ statistics.total - statistics.completed }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 优先级分布 -->
		<view class="priority-section">
			<view class="section-header">
				<text class="section-title">优先级分布</text>
			</view>
			<view class="priority-chart">
				<view 
					v-for="priority in priorityStats" 
					:key="priority.level"
					class="priority-bar"
				>
					<view class="bar-info">
						<text class="bar-label">{{ priority.label }}</text>
						<text class="bar-count">{{ priority.count }}</text>
					</view>
					<view class="bar-container">
						<view 
							class="bar-fill"
							:class="`priority-${priority.level}`"
							:style="{ width: priority.percentage + '%' }"
						></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 标签统计 -->
		<view class="tags-section" v-if="tagStats.length > 0">
			<view class="section-header">
				<text class="section-title">分类统计</text>
			</view>
			<view class="tags-chart">
				<view 
					v-for="tag in tagStats" 
					:key="tag.name"
					class="tag-item"
				>
					<view class="tag-info">
						<text class="tag-name">{{ tag.name }}</text>
						<text class="tag-count">{{ tag.count }}</text>
					</view>
					<view class="tag-bar">
						<view 
							class="tag-fill"
							:style="{ width: tag.percentage + '%' }"
						></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 最近7天趋势 -->
		<view class="trend-section">
			<view class="section-header">
				<text class="section-title">最近7天趋势</text>
			</view>
			<view class="trend-chart">
				<view class="chart-container">
					<view 
						v-for="day in weekTrend" 
						:key="day.date"
						class="trend-bar"
					>
						<view 
							class="trend-fill"
							:style="{ height: day.percentage + '%' }"
						></view>
						<text class="trend-label">{{ day.dayName }}</text>
						<text class="trend-count">{{ day.count }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="actions-section">
			<!-- 导出数据功能暂未完全实现，先隐藏 -->
			<!-- <button class="action-btn" @click="exportData">
				<uni-icons type="download" size="18" color="#3B82F6" />
				<text>导出数据</text>
			</button> -->
			<button class="action-btn full-width" @click="resetStats">
				<uni-icons type="refresh" size="18" color="#6B7280" />
				<text>重置统计</text>
			</button>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
	name: 'StatisticsPage',
	
	computed: {
		...mapGetters('schedule', ['statistics', 'sortedSchedules']),
		
		// 完成度角度（0-360度）
		completionDegree() {
			return (this.statistics.completionRate / 100) * 360
		},
		
		// 优先级统计
		priorityStats() {
			const priorities = ['urgent', 'high', 'medium', 'low']
			const labels = { urgent: '紧急', high: '高', medium: '中', low: '低' }
			const total = this.statistics.total || 1
			
			return priorities.map(level => {
				const count = this.sortedSchedules.filter(s => s.priority === level).length
				return {
					level,
					label: labels[level],
					count,
					percentage: Math.round((count / total) * 100)
				}
			}).filter(item => item.count > 0)
		},
		
		// 标签统计
		tagStats() {
			const tagCounts = {}
			this.sortedSchedules.forEach(schedule => {
				schedule.tags?.forEach(tag => {
					tagCounts[tag] = (tagCounts[tag] || 0) + 1
				})
			})
			
			const total = Object.values(tagCounts).reduce((sum, count) => sum + count, 0) || 1
			
			return Object.entries(tagCounts)
				.map(([name, count]) => ({
					name,
					count,
					percentage: Math.round((count / total) * 100)
				}))
				.sort((a, b) => b.count - a.count)
				.slice(0, 8) // 只显示前8个
		},
		
		// 最近7天趋势
		weekTrend() {
			const days = []
			const today = new Date()
			const dayNames = ['日', '一', '二', '三', '四', '五', '六']
			
			for (let i = 6; i >= 0; i--) {
				const date = new Date(today)
				date.setDate(today.getDate() - i)
				
				const dateString = this.formatDateString(date)
				const daySchedules = this.sortedSchedules.filter(schedule => {
					const scheduleDate = new Date(schedule.endTime)
					return this.formatDateString(scheduleDate) === dateString
				})
				
				days.push({
					date: dateString,
					dayName: dayNames[date.getDay()],
					count: daySchedules.length,
					percentage: 0 // 稍后计算
				})
			}
			
			// 计算百分比（基于最大值）
			const maxCount = Math.max(...days.map(d => d.count), 1)
			days.forEach(day => {
				day.percentage = Math.round((day.count / maxCount) * 100)
			})
			
			return days
		}
	},
	
	onLoad() {
		this.$store.dispatch('schedule/loadSchedules')
	},
	
	onShow() {
		// 更新自定义tabBar选中状态
		if (typeof this.getTabBar === 'function' && this.getTabBar()) {
			this.getTabBar().selected = 2
		}
	},
	
	methods: {
		// 格式化日期字符串
		formatDateString(date) {
			const year = date.getFullYear()
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 重置统计
		resetStats() {
			uni.showModal({
				title: '确认重置',
				content: '重置统计将清空所有日程数据，此操作不可恢复！',
				confirmColor: '#EF4444',
				success: (res) => {
					if (res.confirm) {
						this.$store.commit('schedule/SET_SCHEDULES', [])
						this.$store.dispatch('schedule/saveSchedules')
						
						uni.showToast({
							title: '统计已重置',
							icon: 'success'
						})
					}
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: $background-gray;
	padding: $spacing-lg;
}

.overview-section {
	margin-bottom: $spacing-xl;
}

.stats-card {
	background-color: $card-white;
	border-radius: $border-radius-md;
	padding: $spacing-lg;
	box-shadow: $shadow-sm;
}

.stats-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: $spacing-lg;
}

.stat-item {
	text-align: center;
}

.stat-number {
	display: block;
	font-size: 32px;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
	margin-bottom: $spacing-xs;
	
	&.completed {
		color: $complete-green;
	}
	
	&.urgent {
		color: $urgent-red;
	}
	
	&.overdue {
		color: $high-orange;
	}
}

.stat-label {
	font-size: $font-size-body;
	color: $text-light-gray;
}

.section-header {
	margin-bottom: $spacing-lg;
}

.section-title {
	font-size: $font-size-title-2;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
}

.completion-section {
	margin-bottom: $spacing-xl;
}

.completion-card {
	background-color: $card-white;
	border-radius: $border-radius-md;
	padding: $spacing-xl;
	box-shadow: $shadow-sm;
	display: flex;
	align-items: center;
	gap: $spacing-xl;
}

.progress-circle {
	position: relative;
	width: 120px;
	height: 120px;
	flex-shrink: 0;
}

.circle-bg {
	width: 100%;
	height: 100%;
	border-radius: 50%;
	background-color: $background-gray;
	position: relative;
	overflow: hidden;
}

.circle-fill {
	position: absolute;
	top: 0;
	left: 50%;
	width: 50%;
	height: 100%;
	background-color: $complete-green;
	transform-origin: left center;
	transform: rotate(0deg);
	transition: transform 1s ease;
}

.circle-content {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	text-align: center;
}

.percentage {
	display: block;
	font-size: 24px;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
}

.percentage-label {
	font-size: $font-size-caption;
	color: $text-light-gray;
}

.completion-details {
	flex: 1;
}

.detail-item {
	display: flex;
	align-items: center;
	gap: $spacing-sm;
	margin-bottom: $spacing-md;
}

.detail-dot {
	width: 12px;
	height: 12px;
	border-radius: 50%;
	
	&.completed {
		background-color: $complete-green;
	}
	
	&.pending {
		background-color: $border-gray;
	}
}

.detail-text {
	font-size: $font-size-body;
	color: $text-dark-gray;
}

.priority-section, .tags-section, .trend-section {
	margin-bottom: $spacing-xl;
}

.priority-chart, .tags-chart {
	background-color: $card-white;
	border-radius: $border-radius-md;
	padding: $spacing-lg;
	box-shadow: $shadow-sm;
}

.priority-bar, .tag-item {
	margin-bottom: $spacing-lg;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.bar-info, .tag-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: $spacing-xs;
}

.bar-label, .tag-name {
	font-size: $font-size-body;
	color: $text-dark-gray;
}

.bar-count, .tag-count {
	font-size: $font-size-body;
	font-weight: $font-weight-semibold;
	color: $text-light-gray;
}

.bar-container, .tag-bar {
	height: 8px;
	background-color: $background-gray;
	border-radius: 4px;
	overflow: hidden;
}

.bar-fill {
	height: 100%;
	transition: width 1s ease;
	
	&.priority-urgent {
		background-color: $urgent-red;
	}
	
	&.priority-high {
		background-color: $high-orange;
	}
	
	&.priority-medium {
		background-color: $medium-purple;
	}
	
	&.priority-low {
		background-color: $low-gray;
	}
}

.tag-fill {
	height: 100%;
	background-color: $primary-blue;
	transition: width 1s ease;
}

.trend-chart {
	background-color: $card-white;
	border-radius: $border-radius-md;
	padding: $spacing-lg;
	box-shadow: $shadow-sm;
}

.chart-container {
	display: flex;
	justify-content: space-between;
	align-items: end;
	height: 120px;
	gap: $spacing-sm;
}

.trend-bar {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	height: 100%;
}

.trend-fill {
	width: 100%;
	background-color: $primary-blue;
	border-radius: 2px 2px 0 0;
	transition: height 1s ease;
	margin-bottom: auto;
}

.trend-label {
	font-size: $font-size-caption;
	color: $text-light-gray;
	margin-top: $spacing-xs;
}

.trend-count {
	font-size: $font-size-caption;
	color: $text-dark-gray;
	font-weight: $font-weight-semibold;
}

.actions-section {
	display: flex;
	gap: $spacing-md;
	margin-top: $spacing-xl;
}

.action-btn {
	flex: 1;
	height: 44px;
	background-color: $card-white;
	border: 1px solid $border-gray;
	border-radius: $border-radius-md;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: $spacing-sm;
	font-size: $font-size-body;
	color: $text-dark-gray;
	
	&.full-width {
		flex: none;
		width: 100%;
	}
	
	&:active {
		transform: scale(0.98);
		background-color: $background-gray;
	}
}
</style> 